package cn.xc.user.service.impl;


import cn.xc.basic.constant.VerifyCodeConstant;
import cn.xc.basic.service.impl.BaseServiceImpl;
import cn.xc.basic.util.Md5Utils;
import cn.xc.basic.util.StrUtils;
import cn.xc.org.exception.BusinessException;
import cn.xc.user.domain.Logininfo;
import cn.xc.user.domain.User;
import cn.xc.user.dto.UserDto;
import cn.xc.user.mapper.LogininfoMapper;
import cn.xc.user.mapper.UserMapper;
import cn.xc.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private LogininfoMapper logininfoMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public void phoneRegister(UserDto userDto) {
        String code = userDto.getCode();
        String phone = userDto.getPhone();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();

        //判断输入的数据是否为空
        if (StringUtils.isEmpty(code)|| StringUtils.isEmpty(phone)
            ||StringUtils.isEmpty(password)||StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("你填入的信息为空！");
        }
        //判断两次密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("两次输入的密码不对!");
        }
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstant.REGISTER_CODE_PREFIX + phone);
        if (obj==null){
            throw new BusinessException("验证码過期，請重新請求");
        }
        if (obj.toString().split(":")[0].equals(code)){
            throw new BusinessException("請輸入正確的驗證碼");
        }

        //2.保存数据
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }

    //对象转对象就用这种方式
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则进行拷贝
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//1-表示用户
        return logininfo;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //密码 - 加盐加密之后的
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }
}
